﻿using FastCode.Architecture;
using FastCode.DTO;
using FastCode.Models;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Text;

namespace FastCode.Controllers
{
    public class DBConfigController : ApiControllerBase<DBConfig>
    {
        readonly DBConfigService dBConfigService;
        public DBConfigController(ISqlSugarClient _db, DBConfigService dBConfigService) : base(_db)
        {
            this.dBConfigService = dBConfigService;
        }

        /// <summary>
        /// 获取所有数据库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GetAllDb()
        {
            var allDb = await GetBaseQuery<DBConfig>().ToListAsync();
            //添加框架表
            allDb.Insert(0, new DBConfig
            {
                Id = 0,
                Name = "框架库",
            });
            return Msg.Success(allDb);
        }

        /// <summary>
        /// 获取数据库的表
        /// </summary>
        /// <param name="dBConfig"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GetDbTables(DBConfig dBConfig)
        {
            try
            {

                //var item = await db.Queryable<DBConfig>().FirstAsync(x => x.Id == dBConfig.Id);
                //var testDb = new SqlSugarClient(new ConnectionConfig()
                //{
                //    ConnectionString = item.ConnectStr,
                //    DbType = item.EDBType,
                //    IsAutoCloseConnection = true
                //});

                var tableInfoList = new List<DbTableInfo>();
                //如果是框架库
                if (dBConfig.Id == 0)
                {
                    tableInfoList = db.DbMaintenance.GetTableInfoList();
                }
                else
                {
                    var testDb = await dBConfigService.GetSqlClientAsync(dBConfig.Id);
                    tableInfoList = testDb.DbMaintenance.GetTableInfoList();
                }

                return Msg.Success(tableInfoList);

            }
            catch (Exception ex)
            {
                return Msg.Error(ex.Message);
            }
        }



        /// <summary>
        /// 获取表对应列信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> GetModelClass(DBConfigDTO dto)
        {
            ISqlSugarClient? configDb;
            //if (dto.Id == 0)
            //{
            //    configDb = db;
            //}
            //else
            //{
            //    configDb = await dBConfigService.GetSqlClientAsync(dto.Id);
            //}

            //var columnInfos = configDb.DbMaintenance.GetColumnInfosByTableName(dto.TableName, false);

            var columnInfos = await dBConfigService.GetDbColumnInfoAsync(dto);

            StringBuilder classBuilder = new StringBuilder();


            if (!string.IsNullOrEmpty(dto.TableDescription))
            {
                classBuilder.AppendLine($"/// <summary>");
                classBuilder.AppendLine($"/// {dto.TableDescription}");
                classBuilder.AppendLine($"/// </summary>");
            }

            classBuilder.AppendLine($"public class {dto.TableName}");
            classBuilder.AppendLine("{");
            var attributeIndent = "    ";
            foreach (var item in columnInfos)
            {

                if (!string.IsNullOrEmpty(item.ColumnDescription))
                {
                    classBuilder.AppendLine($"{attributeIndent}/// <summary>");
                    classBuilder.AppendLine($"{attributeIndent}/// {item.ColumnDescription}");
                    classBuilder.AppendLine($"{attributeIndent}/// </summary>");

                }
                var cSharpType = DbTypeConverter.ConvertStringTypeToCSharpType(item.DataType);
                //ctype.Name
                //public String Name{ get; set;}
                var isNullable = item.IsNullable ? "?" : "";
                classBuilder.AppendLine($"{attributeIndent}public {cSharpType.Name}{isNullable} {item.DbColumnName} {{ get; set; }}");
            }

            classBuilder.AppendLine("}");

            return Msg.Success(classBuilder.ToString());
        }


        /// <summary>
        /// 测试连接
        /// </summary>
        /// <param name="dBConfig"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<object> TestConnect(DBConfig dBConfig)
        {

            var testDb = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = dBConfig.ConnectStr,
                DbType = dBConfig.EDBType,
                IsAutoCloseConnection = true
            });

            try
            {
                //执行简单的查询操作以测试连接
                testDb.Ado.CheckConnection();
            }
            catch (Exception ex)
            {
                return Msg.Error(ex.Message);
            }
            return Msg.Success(null);
        }
    }
}
